import got from "got";
import fse from "fs-extra";

// 引入Cookie并处理
const COOKIES_FILE = "./cookies.json";
const COOKIES = fse.readJSONSync(COOKIES_FILE);
const COOKIE = COOKIES.reduce(
    (prev, curr) => prev + `${curr.name}=${curr.value};`,
    "",
);

// 公共请求头
const HEADERS = {
    cookie: COOKIE,
};

// 掘金API地址
const API_BASE_URL = "https://api.juejin.cn/booklet_api/v1";

// 获取小册列表
export const getBookList = async () => {
    // 请求小册列表接口
    const res = await got.post(`${API_BASE_URL}/booklet/bookletshelflist`, {
        headers: HEADERS,
    }).json();

    // 转换为 inquirer.prompt 需要的结构
    return res.data.map((book) => ({
        value: book.booklet_id,
        name: book.base_info.title,
    }));
};

// 获取小册信息和章节列表
export const getBookInfo = async (bookId) => {
    // 获取小册信息
    const response = await got.post(`${API_BASE_URL}/booklet/get`, {
        json: {booklet_id: bookId},
        headers: HEADERS,
    }).json();

    // 封装章节列表
    const bookInfo = response.data.booklet;
    const sectionList = response.data.sections.map((section, index) => ({
        index: index + 1,
        id: section.section_id,
        title: section.title,
        status: section.status
    }));

    return {
        bookInfo,
        sectionList,
    };
};

// 获取章节信息
export const getSection = async (sectionId) => {
    // 请求章节信息接口
    const response = await got.post(`${API_BASE_URL}/section/get`, {
        json: {section_id: sectionId},
        headers: HEADERS,
    }).json();

    // 封装章节标题和内容
    return {
        title: response.data.section.title,
        content: response.data.section.markdown_show,
    };
};

// 下载图片
export const downloadImg = async (imageUrl) => {
    return got.get(imageUrl, {headers: HEADERS}).buffer();
};

// 纠正文件名
export const rectifyFileName = fileName => (
    fileName.replace(/[\/<>\\|?*]/g, match => ({
        '/': "\u2215",
        '<': "\uFE64",
        '>': "\uFE65",
        ':': "\uA789",
        '\\': "\uFE68",
        '|': "\u2758",
        '?': "\uFE16",
        '*': "\uFE61"
    }[match]))
);
